package com.cc.visitor.controller;

import com.cc.alltype.StringUtils;
import com.cc.alltype.alltype.FileUtils;
import com.cc.visitor.annotation.VerifySignature;
import com.cc.visitor.entity.VisitSignatureFile;
import com.cc.visitor.service.VisitSignatureFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.util.UUID;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

/**
 * @author chanchaw
 * @create 2025-01-21 13:51
 */
@CrossOrigin
@RestController
@RequestMapping("/visitSignatureFile")
public class VisitSignatureFileController {
    @Autowired
    private VisitSignatureFileService service;
    @Value("${file.signature.img-path}")
    private String signatureImgPath;

    @VerifySignature
    @PostMapping("/insert")
    public void insert(MultipartFile file, String fileRename, String remark, Integer parentId,
                       String miniId,String unionId,
                       ServletResponse res) throws IOException {
        parentId = parentId == null ? 0:parentId;
        miniId = miniId == null ? "":miniId;
        unionId = unionId == null ? "":unionId;

        // 设置响应的内容类型为text/html，初始化响应对象
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();

        String uuid = getUUID();
        String fileName = file.getOriginalFilename();

        // 保证配置文件中指定的路径最后一个字符是/
        String lastCharacter = signatureImgPath.substring(signatureImgPath.length()-1);
        if( lastCharacter != "/" ) signatureImgPath = signatureImgPath + "/";

        String fileSuffix = FileUtils.getFileSuffix(fileName);
        String fileNameWithSuffix = uuid + "." + fileSuffix;
        String filePath = signatureImgPath + fileNameWithSuffix;

        // 存在同名文件则覆盖
        CopyOption[] options = new CopyOption[]{REPLACE_EXISTING};
        File dest = new File(filePath);
        Files.copy(file.getInputStream(), dest.toPath(), options);
        String destPath = dest.getAbsolutePath();
        System.out.println("上传签名图片文件成功：" + destPath);

        // 写入上传日志
        VisitSignatureFile record = VisitSignatureFile.builder().parentId(parentId)
                .miniId(miniId).unionId(unionId)
                .filenameOriginal(fileName).filenameRename(fileRename)
                .hashString(uuid).extension(fileNameWithSuffix).remark(remark).build();
        service.insert(record);

        // 写入HTML内容和JavaScript代码
//        out.println("<html>");
//        out.println("<head>");
//        out.println("<title>Example Servlet</title>");
//        out.println("</head>");
//        out.println("<body>");
//        out.println("<h1>Servlet Example</h1>");
//        out.println("<script>");
//        out.println("parent.afterUpload();"); // 调用前端JavaScript函数
//        out.println("</script>");
//        out.println("</body>");
//        out.println("</html>");
//        out.close();

        // 将生成图片的UUID返回给前端，制作访单的页面要用到
        // 生成的访单通过该UUID将 visit 和 visit_signature_file 关联起来
        out.println(uuid);
        out.close();
    }

    private String getUUID(){
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-","");
        return uuid;
    }
}
